<?php

namespace app\index\controller;

use app\BaseController;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;
use think\facade\View;
use app\index\validate\User;
use app\common\Ai;

/**
 * @index旅游首页
 * @tourist导游注册页面
 * @login导游登录页面
 * @visitor电子行程卡录入页面
 * @sign电子签名页
 * @signature签名后的主题页面
 * */

class Index extends BaseController
{

    public function index()
    {
        return View::fetch();
    }


    public function tourist()
    {
        return View::fetch('tourist_index');

    }

    public function stourist(Request $request)
    {
            try {
                validate(User::class)->check([
                    'name'  => $request['name'],
                    'iphone' => $request['iphone'],
                    'id_card' => $request['id_card'],
                ]);
            } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                //return ($e->getError());
                return json([
                    "msg" => $e->getError(),
                    "status" => 206,
                ]);
            }

            $pwd = substr($request['iphone'], 7);
            $data = [
                    'openid' => '0',
                    'dyname' => $request['name'],
                    'dyiphone' => $request['iphone'],
                    'zhengjian' => $request['id_card'],
                    'company' => '北京麦盟科技',
                    'dyaddtime' => time(),
                    'pwd' => $pwd,
                    'stutic' => '0'
            ];

            Db::name('daoyou')->insert($data);
            return json([
                "status" => 200,
            ]);       
    }

    public function login()
    {
        return View::fetch('tourist_login');
    } 


    public function visitor()
    {
        return View::fetch('visitor_info_post');
    } 

    public function visitorpost(Request $request)
    {
        try {
            validate(User::class)->check([
                'name'  => $request['name'],
                'iphone' => $request['iphone'],
                'id_card' => $request['base_star_date'],
            ]);
        } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                //return ($e->getError());
            return json([
                "msg" => $e->getError(),
                 "status" => 206,
            ]);
        }

        $data = [
            'd_name' => $request['name'],
            'd_iphone' => $request['iphone'],
            'datetime' => $request['base_star_date'],
            'carNum' => $request['car_id'],
            'sjname' => $request['user_name'],
            'sjiphone' => $request['user_mobile']
        ];

        Db::name('trip')->strict(false)->insert($data);
        return json([
            "status" => 200,
        ]);
    }


    public function visitores(Request $request)
    {
        try {
            validate(User::class)->check([
                'name'  => $request['name'],
                'iphone' => $request['iphone'],
                'id_card' => $request['base_star_date'],
            ]);
        } catch (ValidateException $e) {
                // 验证失败 输出错误信息
                //return ($e->getError());
            return json([
                "msg" => $e->getError(),
                 "status" => 206,
            ]);
        }

        $data = [
            'home_num' => $request['name'],
            'ykname' => $request['iphone'],
            'ykaddtime' => $request['base_star_date'],
            'sfzhengjian' => $request['car_id'],
        ];

        Db::name('trip')->strict(false)->insert($data);
        return json([
            "status" => 200,
        ]);
    }


    public function sign()
    {
        return View::fetch('sign_pact');
    } 


    public function signature()
    {
        return View::fetch();
    }  

    public function idcard(){
        $ai = new Ai();
        $front = $this->request->param('front','');//身份证正面64位数编码
        $back = $this->request->param('back','');//身份证反面64位数编码
        if(!empty($front)) {
            $frontUrl =  $this->uploadsBase($front,'card');//转64为图片。返回图片路径
            $url = app()->getRootPath() . '/public' .$frontUrl ;
            $state = 'front';//传参百度接口使用：正面
        }elseif (!empty($back)){
            $backUrl =  $this->uploadsBase($back,'card');
            $url = app()->getRootPath() . '/public' .$backUrl ;
            $state = 'back';//传参百度接口使用：反面
        }else{
            return $this->renderError('请上传图片');
        }
        $result = $ai->getIdCard($url,$state);
        if ($result['image_status'] == 'normal') {
            unset($result['log_id']);
            unset($result['words_result_num']);
            unset($result['idcard_number_type']);
            unset($result['image_status']);
            // 保存登录状态
            if(!empty($frontUrl)) {//身份证正面头像
                 //获取识别成功后的头像（通用好像没有这个）
                $image = "data:image/jpg;base64," . $result['photo'];
                $path = '.'.preg_replace('/(.*)\/{1}([^\/]*)/i', '$1', $frontUrl);
                $imageName = date("Ymd") . date("His", time()) . "_" . rand(1111, 9999) . '.png';
                if (strstr($image, ",")) {
                    $image = explode(',', $image);
                    $image = $image[1];
                }
                if (!is_dir($path)) { //判断目录是否存在 不存在就创建
                    mkdir($path, 0777, true);
                }
                $imageSrc = $path . "/" . $imageName; //图片名字
                $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
                if (!$r) {
                    $tmparr1 = array('data' => null, "code" => 1, "msg" => "图片生成失败");
                    echo json_encode($tmparr1);
                } else {
                    $tmparr2 = array('data' => 1, "code" => 0, "msg" => "图片生成成功");
                    echo json_encode($tmparr2);
                }
            }
            return $this->renderSuccess('身份证识别成功',$result );
        } else {
            return $this->renderError('身份证识别失败', $result);
        }
    }

}